package com.buttonpay.home;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.buttonpay.R;

public class TransactionHistory extends Activity
{
	Button btnLogout,btnBack;
	
	ListView list_transaction;
	ProgressDialog pd= null;
	Handler handler= new Handler();
	 
	String[] values = new String[] 
			{
	          	"Last Transactions","Transaction Query"
	    	};
	Integer[] images=new Integer[]
			{
				R.drawable.change_password,
				R.drawable.change_transaction_pin,
			};
 
	 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==22)
		{
			setResult(2);
	    	finish();	
		}
		
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.transaction_history);
		list_transaction=(ListView)findViewById(R.id.list_transactionDetails);
		btnLogout=(Button)findViewById(R.id.btnLogout);
        btnBack=(Button)findViewById(R.id.btnPrevious);
        
        
        
        TextView tv_header=(TextView)findViewById(R.id.tv_headerText);
        tv_header.setText("Transaction History"); 
          
		MyListAdapter adapter = new MyListAdapter(this, values,images);
		list_transaction.setAdapter(adapter);
		
		
		list_transaction.setOnItemClickListener(new OnItemClickListener()
		{

			public void onItemClick(AdapterView<?> adapterView, View view, int position,long id)
			{
				if(position==0)
				{
					AlertDialog alert=createDialog(new CharSequence[]{"Last Day","Last Week","Custom Search"});
					alert.show();
				}
				else if(position==1)
				{
					new TransactionQuery(TransactionHistory.this).show();
				}
			}
		});
		
	  
        btnLogout.setOnClickListener(new OnClickListener()
        {
        	
        	public void onClick(View arg0) 
			{
        		new AlertDialog.Builder(TransactionHistory.this)
		        .setTitle( "Exit Application")
		        .setMessage( "Are you sure you want to Logout?" )
		        .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
		        {
		            public void onClick(DialogInterface arg0, int arg1) 
		            {
		                //do stuff onclick of YES
		            	setResult(2);
		            	finish();
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub
						
					}
		        })
		        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() 
		        {
		            public void onClick(DialogInterface arg0, int arg1)
		            {
		                //do stuff onclick of CANCEL
		            	arg0.dismiss();
		               
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub
					}
		        }).show();
				// TODO Auto-generated method stub
				  
			}
        	
		});
        
        btnBack.setOnClickListener(new OnClickListener()
        {
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				finish();
			}
		});
        
	}
	 
	protected AlertDialog createDialog(CharSequence[] items) 
	{
		AlertDialog.Builder builder=new AlertDialog.Builder(TransactionHistory.this);
		
		builder.setItems(items, new DialogInterface.OnClickListener() 
		{
			
			public void onClick(DialogInterface dialog, int position) 
			{
				
				 Date currentDate= new Date();
				 int day=currentDate.getDate();
				 int month=currentDate.getMonth();
				 int year=currentDate.getYear();   
				 
				if(position==0)
				{
					 
					 Date previousDate=new Date(year, month, day-1);
					 System.out.println("Current Date:"+formatter.format(currentDate)+
							 			"\nPrevious Date:"+formatter.format(previousDate));
					 String strcurrentDate,strpreviousDate;
					 
					 strcurrentDate=formatter.format(currentDate);
					 strpreviousDate=formatter.format(previousDate);
					 pd=ProgressDialog.show(TransactionHistory.this,"please wait.",null);
				     pd.setContentView(R.layout.progress);
					 new Thread(new GetTransactionRunnable(TransactionHistory.this, pd, handler,strpreviousDate,strpreviousDate)).start();
					
				}
				else if(position==1)
				{
					Date previousDate=new Date(year, month, day-7);
					 System.out.println("Current Date:"+formatter.format(currentDate)+
							 			"\nPrevious Date:"+formatter.format(previousDate));
					 String strcurrentDate,strpreviousDate;
					 
					 strcurrentDate=formatter.format(currentDate);
					 strpreviousDate=formatter.format(previousDate);
					 pd=ProgressDialog.show(TransactionHistory.this,"please wait.",null);
				     pd.setContentView(R.layout.progress);
					 new Thread(new GetTransactionRunnable(TransactionHistory.this, pd, handler,strcurrentDate,strpreviousDate)).start();
				}
				else if(position==2)
				{
					//showDialog(DATE_DIALOG_ID);
					new DateDialog(TransactionHistory.this).show();
				}
				
			}
		});
		AlertDialog alert=builder.create();
		
		return alert;
		
	}
	
	 public static class ViewHolder
	 {
			public TextView tvItemName;
			public ImageView ivItemImage;
			 
     }
	 class MyListAdapter extends ArrayAdapter<String> 
	 {
			
			private final Context context;
			private final String[] values;
			private final Integer[] images;
			LayoutInflater vi ;
		  
			public MyListAdapter(Context context, String[] values, Integer[] images)
			{
				super(context, R.layout.row_lv_settings,values);
				
				this.context = context;
				this.values = values; 
				this.images=images;
				vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			}
			
			public View getView(final int position, View convertView, ViewGroup parent) 
			{
				 View v = convertView;
				 ViewHolder holder = null;
				 
				if (v == null) 
				{
						holder=new ViewHolder();  
						v = vi.inflate(R.layout.row_lv_settings, null); 
						holder.tvItemName=(TextView) v.findViewById(R.id.tvItemName);
						holder.ivItemImage=(ImageView)v.findViewById(R.id.ivOperatorIcon);
						v.setTag(holder);
				}
				else
					holder=(ViewHolder)v.getTag();
					String name=this.values[position];
					System.out.println(name);
					holder.tvItemName.setText(name);
					holder.ivItemImage.setImageResource(this.images[position]);
					  
				 	return v; 
			}
		}	
	 protected class DateDialog extends Dialog implements android.view.View.OnClickListener
	 {
		 Button btnOk;
		 DatePicker fromDate,toDate;
		 
		 
		 public DateDialog(Context context) 
		 {
			 super(context);
			 requestWindowFeature(Window.FEATURE_NO_TITLE);
			 setContentView(R.layout.date_layout);
			 btnOk=(Button)findViewById(R.id.button1);
			 fromDate=(DatePicker)findViewById(R.id.datePickerFromDate);
			 toDate=(DatePicker)findViewById(R.id.datePickerToDate); 
			 btnOk.setOnClickListener(this);
		}


		public void onClick(View v) 
		{
			 
			System.out.println("From Date:"+fromDate.getDayOfMonth()+","+fromDate.getMonth()+","+fromDate.getYear());
			System.out.println("To Date:"+toDate.getDayOfMonth()+","+toDate.getMonth()+","+toDate.getYear());
			dismiss();
			Date pDate=new Date(fromDate.getYear()-1900,fromDate.getMonth(),fromDate.getDayOfMonth());
			Date cDate=new Date(toDate.getYear()-1900,toDate.getMonth(),toDate.getDayOfMonth());
			String strcurrentDate,strpreviousDate;
			 
			 strcurrentDate=formatter.format(cDate);
			 strpreviousDate=formatter.format(pDate);
			 pd=ProgressDialog.show(TransactionHistory.this,"please wait.",null);
		     pd.setContentView(R.layout.progress);
			 new Thread(new GetTransactionRunnable(TransactionHistory.this, pd, handler,strcurrentDate,strpreviousDate)).start();
		}
		 
	 }
	 protected class TransactionQuery extends Dialog implements OnClickListener
	 {
			private Context context;
			private EditText etRefNo;
			private Button btnOk,btnCancel;
			 
			 public TransactionQuery(Context context) 
			 {
				super(context);
				this.context=context;
				requestWindowFeature(Window.FEATURE_NO_TITLE);
				setContentView(R.layout.transaction_query_dialog);
				etRefNo=(EditText)findViewById(R.id.etReferenceNumber);
			    btnOk=(Button)findViewById(R.id.btn_ok);
				btnCancel=(Button)findViewById(R.id.btn_Cancel);
				btnOk.setOnClickListener(this);
				btnCancel.setOnClickListener(this);
			 }
			 public void onClick(View v) 
			 {
				if (v == btnOk)
				{
					if(etRefNo.getText().toString().trim().length()>0)
					{
						pd=ProgressDialog.show(TransactionHistory.this,"please wait.",null);
				        pd.setContentView(R.layout.progress);
				        
				        Thread thread=new Thread(new GetTransactionRunnable(this,TransactionHistory.this, pd, handler,etRefNo.getText().toString()));
				        thread.start();
					}
					else
					{
						Toast.makeText(	TransactionHistory.this,"Please Enter Reference Number.",Toast.LENGTH_SHORT).show();
					}
				}
				else if(v==btnCancel)
				{
					dismiss();
				}
		     }  
	 }//transaction dialog
	 
	 
}
